package com.shenghua.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shenghua.dao.mapper.AppFileMapper;
import com.shenghua.dao.model.AppFile;
import com.shenghua.dao.model.AppFileExample;
import com.shenghua.dao.model.Mould;
import com.shenghua.dao.model.User;
import com.shenghua.dao.page.Page;
import com.shenghua.service.MouldService;
import com.shenghua.shiro.ShiroUtil;
import com.shenghua.utils.ListUtils;
import com.shenghua.utils.PicUtil;
import com.shenghua.utils.StringUtils;
import com.shenghua.utils.beans.Constants;
import com.shenghua.utils.beans.Dto;
import com.shenghua.utils.beans.ErrorCode;
import com.shenghua.utils.constants.FileType;
import com.shenghua.utils.constants.OperateType;
import com.shenghua.logs.operatelogs.OperateLogsAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by Administrator on 2018/12/27.
 */
@Controller
@RequestMapping("/")
public class MouldController extends BaseController{
    Logger logger = LoggerFactory.getLogger(MouldController.class);
    @Resource
    private MouldService mouldService;

    @Autowired
    private AppFileMapper appFileMapper;

    @Value("${app-path}")
    private  String appPath;

    @RequestMapping(value = "/addMould")
    //@OperateLogsAnnotation(operation = OperateType.GET_PAGE, desc = "添加模具页面")
    public String addMouldPage() {
        return "page/addMould";
    }
    @RequestMapping(value = "/addMould/mobile")
    //@OperateLogsAnnotation(operation = OperateType.GET_PAGE, desc = "添加模具手机页面")
    public String addMouldPage_Mobile() {
        return "phone/addMould";
    }
    @RequestMapping(value = "/addMould/normal")
    //@OperateLogsAnnotation(operation = OperateType.GET_PAGE, desc = "添加模具电脑页面")
    public String addMouldPage_Normal() {
        return "pc/mould/addMould";
    }
    @RequestMapping(value = "/mouldSwiper/normal")
    public String mouldSwiper_Normal() {
        return "pc/mould/mouldSwiper";
    }

    @RequestMapping(value = "/mouldManager")
    public String queryMouldPage() {
        return "page/mouldManager";
    }
    @RequestMapping(value = "/mouldManager/mobile")
    public String queryMouldPage_Mobile() {
        return "phone/mouldManager";
    }
    @RequestMapping(value = "/mouldManager/normal")
    public String queryMouldPage_Normal() {
        return "pc/mould/mouldManager";
    }

    //跳转模具编辑页面
    @RequestMapping(value = "/editMould/normal/{id}")
    public String editMouldPage(@PathVariable(name = "id") Integer id,
                                HttpServletRequest request,Model model) {
        logger.info("编辑的模具id："+id);
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user) {
            logger.debug("[MouldController] editMouldPage 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == id){
            logger.info("[MouldController] editMouldPage 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        Mould mould = mouldService.selectMouldById(id);
        if(null == mould){
            logger.debug("[MouldController] editMouldPage 模具信息不存在");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return JSON.toJSONString(dto);
        }
        AppFileExample appFileExample = new AppFileExample();
        AppFileExample.Criteria criteria = appFileExample.createCriteria();
        criteria.andFileBelongtoEqualTo(mould.getId().toString());
        List<AppFile> appFiles = appFileMapper.selectByExample(appFileExample);
        if(ListUtils.isNotEmpty(appFiles)) {
            for(AppFile appFile : appFiles) {
                appFile.setFilePath(Constants.staticPrefix + Constants.imagePath + appFile.getFilePath());
            }
            mould.setAppFileList(appFiles);
        }
        //model.addAttribute("mould", mould);
        /*if(mould.getPicAddr() != null && !"".equals(mould.getPicAddr())) {
            mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
        }*/
        request.setAttribute("mould",mould);
        return "pc/mould/editMould";
    }

    // 查询详情页面
    @RequestMapping(value = "/mouldDetail/normal/{id}")
    public String mouldDetailPage(@PathVariable(name = "id") Integer id,
                                  HttpServletRequest request,Model model) {
        logger.info("模具详情id："+id);
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user) {
            logger.debug("[MouldController] mouldDetailPage 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == id){
            logger.info("[MouldController] mouldDetailPage 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        Mould mould = mouldService.selectMouldById(id);
        if(null == mould){
            logger.debug("[MouldController] mouldDetailPage 模具信息不存在");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return JSON.toJSONString(dto);
        }

        AppFileExample appFileExample = new AppFileExample();
        AppFileExample.Criteria criteria = appFileExample.createCriteria();
        criteria.andFileBelongtoEqualTo(mould.getId().toString());
        List<AppFile> appFiles = appFileMapper.selectByExample(appFileExample);
        if(ListUtils.isNotEmpty(appFiles)) {
            for(AppFile appFile : appFiles) {
                appFile.setFilePath(Constants.staticPrefix + Constants.imagePath + appFile.getFilePath());
            }
            mould.setAppFileList(appFiles);
        }
        //model.addAttribute("mould", mould);
        /*if(mould.getPicAddr() != null && !"".equals(mould.getPicAddr())) {
            mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
        }*/
        request.setAttribute("mould", mould);
        return "pc/mould/mouldDetail";
    }

    // 新增模具信息
    @RequestMapping(value = "/addNewMould1", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addNewMould1(Mould mould,
               HttpServletRequest request) {
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user){
            logger.debug("[MouldController] addNewMould 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == mould) {
            logger.info("[MouldController] addNewMould 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        logger.info("[MouldController] addNewMould 新增模具信息："+JSON.toJSONString(mould));

        /*MultipartFile picAddr = null;
        if (request instanceof MultipartHttpServletRequest){
            picAddr = ((MultipartHttpServletRequest)request).getFile("pic");
        }*/

        /*logger.info("[MouldController] addNewMould 图片是否为空："+(picAddr==null));
        if(null == picAddr){
            dto.ReturnFail(new Mould(), ErrorCode.FILE_UPLOAD_FIAL);
            return JSON.toJSONString(dto);
        }*/
        /*String uploadUrl = PicUtil.generateImageFileName(picAddr);// 生成新文件名
        String basePath = request.getSession().getServletContext().getRealPath(Constants.imagePath);
        // 根据系统类型不同进行不同的操作
        Properties properties = System.getProperties();
        String os = properties.getProperty("os.name");
        Dto<String> ret = new Dto<>();
        if(os.contains("Windows")) {
            ret = PicUtil.uploadImageInWindows(picAddr, uploadUrl, basePath);
        } else {
            ret = PicUtil.uploadImageInLinux(picAddr, uploadUrl, basePath);
        }*/
        String picAddr = mould.getPicAddr();
        String newFileName = "";
        if(null != picAddr && !"".equals(picAddr)) {// 有上传图片，则保存图片
            /*File p = null; // 文件存到classpth路径下
            try {
                p = new File(ResourceUtils.getURL("classpath:").getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if(!p.exists()){
                p=new File("");
            }
            String basePath = p.getAbsolutePath();
            String basePath1 = p.getAbsolutePath();*/
            String basePath = appPath;
            String basePath1 = appPath;
            //String basePath = request.getSession().getServletContext().getRealPath("/");
            File file = new File(basePath + picAddr.replace(Constants.staticPrefix,""));
            newFileName = file.getName();
            //String basePath1 = request.getSession().getServletContext().getRealPath(Constants.imagePath);
            if(basePath1.endsWith("/") || basePath1.endsWith("\\")
                    || basePath1.endsWith(File.separator))
            {
                basePath1 += Constants.imagePath;
            } else {
                basePath1 += File.separator + Constants.imagePath;
            }
            boolean ret = false;
            if(file.exists()){
                ret = file.renameTo(new File(basePath1+newFileName));
            }
            if(ret) {// 图片上传成功，则修改图片地址
                mould.setPicAddr(Constants.imagePath + newFileName);
                mould.setEntryUserid(user.getId().toString());
                mould.setEntryNickname(user.getNickname());
                dto = mouldService.addNewMould(mould);
                dto.ReturnSuccess(new Mould(), ErrorCode.FILE_UPLOAD_SUCCESS);
            } else {
                mould.setEntryUserid(user.getId().toString());
                mould.setEntryNickname(user.getNickname());
                dto = mouldService.addNewMould(mould);
                dto.ReturnSuccess(new Mould(), ErrorCode.FILE_UPLOAD_FIAL);
            }
        } else {
            mould.setEntryUserid(user.getId().toString());
            mould.setEntryNickname(user.getNickname());
            dto = mouldService.addNewMould(mould);
            dto.ReturnSuccess(mould, ErrorCode.MOULD_ADD_SUCCESS);
        }
        return JSON.toJSONString(dto);
    }

    // 新增模具信息
    @RequestMapping(value = "/addNewMould", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addNewMould(Mould mould,
                              HttpServletRequest request) {
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user){
            logger.debug("[MouldController] addNewMould 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == mould) {
            logger.info("[MouldController] addNewMould 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        logger.info("[MouldController] addNewMould 新增模具信息："+JSON.toJSONString(mould));

        String picAddr = mould.getPicAddr();

        mould.setEntryUserid(user.getId().toString());
        mould.setEntryNickname(user.getNickname());
        dto = mouldService.addNewMould(mould);
        mould = dto.getData();
        if(null != picAddr && !"".equals(picAddr)) {// 有上传图片，则保存图片
            String[] fileIds = picAddr.split(",");
            for(String fileId : fileIds) {
                AppFile appFile = appFileMapper.selectByPrimaryKey(fileId);
                if(appFile != null && StringUtils.isBlank(appFile.getFileBelongto())) {
                    appFile.setFileBelongto(mould.getId() == null ? "" : mould.getId().toString());
                    appFile.setFileType(FileType.FILE_TYPE_MOULD.type);
                    appFileMapper.updateByPrimaryKey(appFile);
                }
            }
        }
        dto.ReturnSuccess(mould, ErrorCode.MOULD_ADD_SUCCESS);
        return JSON.toJSONString(dto);
    }

    //查询模具信息
    @RequestMapping(value = "/selectMouldByPage",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    //@OperateLogsAnnotation(operation = OperateType.QUERY, desc = "查询模具信息")
    public String selectMouldByPage(@RequestParam Map<String,Object> params) {
        Dto<Map<String,Object>> dto = new Dto<>();
        Page page = getRequestPageInfo(params);
        logger.info("[MouldController]selectMouldByPage page:{}", JSON.toJSONString(page));
        dto = mouldService.queryMouldByPage(params, page);
        return JSON.toJSONString(dto);
    }

    //手机端查询模具信息
    @RequestMapping(value = "/countMould/mobile",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String countMould_Mobile_POST(@RequestParam Map<String,Object> params) {
        Dto<Map<String,Object>> dto = new Dto<>();
        dto = mouldService.countMould(params);
        return JSON.toJSONString(dto);
    }

    //手机端查询模具信息
    @RequestMapping(value = "/selectMouldByPage/mobile",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public String selectMouldByPage_Mobile_GET(@RequestParam Map<String, Object> params, Model model) {
        Dto<Map<String,Object>> dto = new Dto<>();
        logger.info("[NoticeController] selectMouldByPage_Mobile_GET 开始查询");
        int pageNo = 1;
        if(StringUtils.isNotBlank(params.get("pageNo"))) {
            pageNo = Integer.parseInt(params.get("pageNo").toString());
        }
        Page page = new Page(pageNo,3);
        dto = mouldService.queryMouldByPage(params, page);
        model.addAttribute("total", dto.getData().get("total"));
        model.addAttribute("data", dto.getData().get("rows"));
        logger.info("[NoticeController] selectMouldByPage_Mobile_GET 查询结果：", JSONObject.toJSON(dto));
        return "phone/mouldList";
    }

    // 删除模具
    @RequestMapping(value = "/deleteMould",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String deleteMould(@RequestParam int id, HttpServletRequest request,
                              HttpServletResponse response) {
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user){
            logger.debug("[MouldController] deleteMould 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        Mould mould = mouldService.selectMouldById(id);
        if(null == mould) {
            logger.debug("[MouldController] deleteMould 模具不存在！");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return JSON.toJSONString(dto);
        }
        //String basePath = request.getSession().getServletContext().getRealPath("/");
        /*File p = null; // 文件存到classpth路径下
        try {
            p = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(!p.exists()){
            p=new File("");
        }
        String basePath = p.getAbsolutePath();*/
        String basePath = appPath;
        logger.info("[MouldController] deleteMould 文件路径：" + basePath);
        if(basePath.endsWith("/") || basePath.endsWith("\\")
                || basePath.endsWith(File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        String picAddr = mould.getPicAddr();
        // 根据系统类型不同进行不同的操作
        Properties properties = System.getProperties();
        String os = properties.getProperty("os.name");
        if(null != picAddr && !"".equals(picAddr)){
            if(os.contains("Windows")){
                mould.setPicAddr(basePath + picAddr);
            }
            logger.debug("[MouldController] deleteMould 图片地址："+mould.getPicAddr());
        }
        dto = mouldService.deleteMould(mould);
        return JSON.toJSONString(dto);
    }

    //编辑模具信息
    @RequestMapping(value = "/editCurrentMould1",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editCurrentMould1(Mould mould, HttpServletRequest request){
        logger.info("编辑的模具信息："+JSON.toJSONString(mould));
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user) {
            logger.debug("[MouldController] editCurrentMould 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == mould || null == mould.getId() || "".equals(mould.getId())) {
            logger.info("[MouldController] editCurrentMould 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        Mould mould1 = mouldService.selectMouldById(mould.getId());
        if(null == mould1){
            logger.debug("[MouldController] editCurrentMould 模具信息不存在");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return JSON.toJSONString(dto);
        }
        mould.setUpdateUserid(user.getId().toString());
        mould.setUpdateNickname(user.getNickname());
        String picAddr = mould.getPicAddr();
        if(null != picAddr && !"".equals(picAddr) && picAddr.contains(Constants.tempImagePath)){
            // 重新选择了图片，需要上传
            /*File p = null; // 文件存到classpth路径下
            try {
                p = new File(ResourceUtils.getURL("classpath:").getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if(!p.exists()){
                p=new File("");
            }
            String basePath = p.getAbsolutePath();*/
            String basePath = appPath;
            //String basePath = request.getSession().getServletContext().getRealPath("/");
            File file = new File(basePath + picAddr.replace(Constants.staticPrefix, ""));
            String basePath1 = appPath;
            if(!(basePath1.endsWith("/") || basePath1.endsWith("\\")
                    || basePath1.endsWith(File.separator))) {
                basePath1 += File.separator + Constants.imagePath;
            } else {
                basePath1 += Constants.imagePath;
            }
            //String basePath1 = request.getSession().getServletContext().getRealPath(Constants.imagePath);
            boolean ret = false;
            if(file.exists()) {
                ret = file.renameTo(new File(basePath1 + file.getName()));
            }
            if(!ret) {
                logger.debug("[MouldController] editCurrentMould 图片修改失败");
                dto.ReturnFail(mould,ErrorCode.MOULD_EDIT_PIC_SUCCESS);
                return JSON.toJSONString(dto);
            } else {
                mould.setPicAddr(Constants.imagePath + file.getName());
            }
        }
        mould.setPicAddr(mould.getPicAddr().replace(Constants.staticPrefix,""));
        dto = mouldService.editMould(mould);
        return JSON.toJSONString(dto);
    }

    //编辑模具信息
    @RequestMapping(value = "/editCurrentMould",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String editCurrentMould(Mould mould, HttpServletRequest request){
        logger.info("编辑的模具信息："+JSON.toJSONString(mould));
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user) {
            logger.debug("[MouldController] editCurrentMould 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == mould || null == mould.getId() || "".equals(mould.getId())) {
            logger.info("[MouldController] editCurrentMould 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        Mould mould1 = mouldService.selectMouldById(mould.getId());
        if(null == mould1){
            logger.debug("[MouldController] editCurrentMould 模具信息不存在");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return JSON.toJSONString(dto);
        }
        mould.setUpdateUserid(user.getId().toString());
        mould.setUpdateNickname(user.getNickname());
        dto = mouldService.editMould(mould);
        String picAddr = mould.getPicAddr();

        if(null != picAddr && !"".equals(picAddr)) {// 有上传图片，则保存图片
            String[] fileIds = picAddr.split(",");
            for(String fileId : fileIds) {
                AppFile appFile = appFileMapper.selectByPrimaryKey(fileId);
                if(appFile != null && StringUtils.isBlank(appFile.getFileBelongto())) {
                    appFile.setFileBelongto(mould.getId() == null ? "" : mould.getId().toString());
                    appFile.setFileType(FileType.FILE_TYPE_MOULD.type);
                    appFileMapper.updateByPrimaryKey(appFile);
                }
            }
        }
        return JSON.toJSONString(dto);
    }

    // 手机查询详情
    @RequestMapping(value = "/mouldDetail/mobile/{id}",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public String mouldDetailPage_Mobile(@PathVariable(name = "id") Integer id,
                                  HttpServletRequest request,Model model) {
        logger.info("模具详情id："+id);
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user) {
            logger.debug("[MouldController] mouldDetailPage 用户未登录");
            return "phone/index";
        }
        if(null == id){
            logger.info("[MouldController] mouldDetailPage 参数不能为空");
            return "phone/queryMould";
        }
        Mould mould = mouldService.selectMouldById(id);
        if(null == mould){
            logger.debug("[MouldController] mouldDetailPage 模具信息不存在");
            return "phone/queryMould";
        }
        if(mould.getPicAddr() != null && !"".equals(mould.getPicAddr())) {
            mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
        }
        model.addAttribute("mould", mould);
        return "phone/mouldDetail";
    }

    // 根据Id查询模具信息，用于修改页面的重置功能
    @RequestMapping(value = "/selectMould/{mouldId}",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String selectMouldById(@PathVariable(name = "mouldId") Integer id,
                                  HttpServletRequest request) {
        logger.info("模具详情id："+id);
        Dto<Mould> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user) {
            logger.debug("[MouldController] selectMould 用户未登录");
            dto.ReturnFail(new Mould(),ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == id){
            logger.info("[MouldController] selectMould 参数不能为空");
            dto.ReturnFail(new Mould(),ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        Mould mould = mouldService.selectMouldById(id);
        if(null == mould){
            logger.debug("[MouldController] selectMould 模具信息不存在");
            dto.ReturnFail(new Mould(),ErrorCode.MOULD_NOT_EXISTS);
            return JSON.toJSONString(dto);
        }
        logger.info("[MouldController] selectMould 模具信息查询成功"+ JSON.toJSONString(mould));
        mould.setPicAddr(Constants.staticPrefix + mould.getPicAddr());
        dto.ReturnSuccess(mould,ErrorCode.MOULD_SELECT_SUCCESS);
        return JSON.toJSONString(dto);
    }

    // 上传临时图片
    @RequestMapping(value = "/uploadTempMouldPic", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String uploadTempMouldPic(@RequestParam(name="picAddr") String picAddr,
                                     HttpServletRequest request) {
        Dto<String> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user){
            logger.debug("[MouldController] uploadTempMouldPic 用户未登录");
            dto.ReturnFail(null,ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        MultipartFile file = null;
        if (request instanceof MultipartHttpServletRequest){
            file = ((MultipartHttpServletRequest)request).getFile("pic");
        }
        logger.info("[MouldController] uploadTempMouldPic 上传临时文件："+JSON.toJSONString(file.getOriginalFilename()));
        logger.info("[MouldController] uploadTempMouldPic 图片是否为空："+(file==null));
        if(null == file){
            dto.ReturnFail(null, ErrorCode.TEMPFILE_UPLOAD_FIAL);
            return JSON.toJSONString(dto);
        }
        String uploadUrl = PicUtil.generateImageFileName(file);// 生成新文件名
        //String basePath = request.getSession().getServletContext().getRealPath(Constants.tempImagePath);
        String basePath = appPath;
        /*File p = null; // 文件存到classpth路径下
        try {
            p = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(!p.exists()){
            p = new File("");
        }
        String basePath = p.getAbsolutePath();*/
        logger.info("[MouldController] uploadTempMouldPic 临时文件路径：" + basePath);
        if(basePath.endsWith("/") || basePath.endsWith("\\")
                || basePath.endsWith(File.separator))
        {
            basePath = basePath.substring(0,basePath.length() - 1) + Constants.tempImagePath;
        } else {
            basePath += Constants.tempImagePath;
        }
        // 根据系统类型不同进行不同的操作
        Properties properties = System.getProperties();
        String os = properties.getProperty("os.name");
        Dto<String> ret = new Dto<>();
        // 开始上传临时文件
        logger.info("[MouldController] uploadTempMouldPic 开始上传临时文件");
        if(os.contains("Windows")) {
            ret = PicUtil.uploadImageInWindows(file, uploadUrl, basePath);
        } else {
            ret = PicUtil.uploadImageInLinux(file, uploadUrl, basePath);
        }
        if(!ret.isSuccess()){
            logger.info("[MouldController] uploadTempMouldPic 临时文件上传失败");
           dto.ReturnFail(null, ErrorCode.TEMPFILE_UPLOAD_FIAL);
        }
        // 删除原来的临时文件
        if(null != picAddr && !"".equals(picAddr) && picAddr.contains(Constants.tempImagePath)){
            logger.info("[MouldController] uploadTempMouldPic 需要删除原来的临时文件！");
            //String basePath1 = request.getSession().getServletContext().getRealPath("/");
            String basePath1 = appPath;
            if(basePath1.endsWith("/") || basePath1.endsWith("\\")
                    || basePath1.endsWith(File.separator))
            {
                basePath1 = basePath1.substring(0,basePath1.length() - 1);
            }
            File file1 = new File(basePath1 + picAddr.replace(Constants.staticPrefix, ""));
            logger.info("[MouldController] uploadTempMouldPic 原来的临时文件地址：" + (basePath1 + picAddr.replace(Constants.staticPrefix, "")));
            if(file1.exists()){
                logger.info("[MouldController] uploadTempMouldPic 开始删除原来的临时文件！");
                boolean ret1 = file1.delete();
                if(!ret1){
                    logger.info("[MouldController] uploadTempMouldPic 原来的临时文件删除失败");
                } else {
                    logger.info("[MouldController] uploadTempMouldPic 原来的临时文件删除成功");
                }
            }
        }
        dto.ReturnSuccess(Constants.staticPrefix + Constants.tempImagePath + ret.getData(),
                ErrorCode.TEMPFILE_UPLOAD_SUCCESS);
        return JSON.toJSONString(dto);
    }

    // 修改页面重置信息功能-删除临时图片
    @RequestMapping(value = "/DeleteTempMouldPic", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String DeleteTempMouldPic(@RequestParam(name="picAddr") String picAddr, HttpServletRequest request) {
        Dto<String> dto = new Dto<>();
        //User user = (User)request.getSession().getAttribute("userSession");
        User user = ShiroUtil.getUser();
        if(null == user){
            logger.debug("[MouldController] DeleteTempMouldPic 用户未登录");
            dto.ReturnFail(null,ErrorCode.USER_NOT_LOGIN);
            return JSON.toJSONString(dto);
        }
        if(null == picAddr || "".equals(picAddr)){
            logger.info("[MouldController] DeleteTempMouldPic 参数不能为空");
            dto.ReturnFail(null,ErrorCode.PARAMETER_IS_NULL);
            return JSON.toJSONString(dto);
        }
        // 删除原来的临时文件
        if(null != picAddr && picAddr.contains(Constants.tempImagePath)){
            //String basePath = request.getSession().getServletContext().getRealPath("/");
            /*File p = null;
            try {
                p = new File(ResourceUtils.getURL("classpath:").getPath());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if(!p.exists()) {
                p = new File("");
            }
            String basePath = p.getAbsolutePath(); */
            String basePath = appPath;
            if(basePath.endsWith("/") || basePath.endsWith("\\")
                    || basePath.endsWith(File.separator))
            {
                basePath = basePath.substring(0, basePath.length() - 1) + Constants.tempImagePath;
            } else {
                basePath += Constants.tempImagePath;
            }
            File file = new File(basePath + picAddr);
            boolean ret = false;
            if(file.exists()){
                ret = file.delete();
                if(!ret){
                    logger.info("[MouldController] DeleteTempMouldPic 临时文件删除失败");
                    dto.ReturnFail(null, ErrorCode.TEMPFILE_DELETE_FIAL);
                }
            } else {
                logger.info("[MouldController] DeleteTempMouldPic 临时文件不存在");
                dto.ReturnFail(null, ErrorCode.TEMPFILE_NOT_EXISTS);
            }
        }
        dto.ReturnSuccess(null, ErrorCode.TEMPFILE_DELETE_SUCCESS);
        return JSON.toJSONString(dto);
    }

    //查询模具信息
    @RequestMapping(value = "/mouldSwiper/load",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String loadMouldSwiper() {
        Dto<Map<String,Object>> dto = new Dto<>();
        dto = mouldService.queryMouldSwiper();
        return JSON.toJSONString(dto);
    }
}
